import fetch from 'dva/fetch';
import {fromJson} from './utils';
import {getLoginSession} from '../plugin/loginSession';

function autoUrlParams(url, params) {
	 if(params) {
	 	let paramUri = '';
    	for (var key in params){
        	paramUri += key + '=' + params[key] + '&';
        }
    	paramUri = paramUri.replace(/&$/g, '');
    	if(paramUri) {
    		url = url + '?' + paramUri;
    	}
    }
	return url;
}

export default function upload(url, blob, fileName, params={}) {
	return new Promise((resolve, reject) => {
		let loginSession = getLoginSession();
		// token注入
		if(loginSession && loginSession.token) {
			let token = loginSession.token;
			params.channel = token.channel;
			params.token = token.token;
		}
		let formData = new FormData();
		formData.append('files', blob, fileName);
		let request = new XMLHttpRequest();
		request.open('POST', autoUrlParams(url, params));
		request.onreadystatechange = () => {
			if(request.readyState == 4) {
		        if(request.status == 200) {
		            resolve(fromJson(request.responseText));
		        } else {
		           reject();
		        }
		    }
		}
		request.send(formData);
	});
}